package org.xx.armory.commons;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.Map;

public final class MapBuilder {
    private final Deque<Map<String, Object>> stack;

    private MapBuilder() {
        this.stack = new ArrayDeque<>();
        this.stack.push(new LinkedHashMap<>());
    }

    public static MapBuilder create() {
        return new MapBuilder();
    }

    public MapBuilder beginEntry(
            String key
    ) {
        if (this.stack.isEmpty()) {
            throw new IllegalStateException("Empty builder");
        }

        final var m = new LinkedHashMap<String, Object>();
        this.stack.peek().put(key, m);
        this.stack.push(m);
        return this;
    }

    public MapBuilder put(
            String key,
            Object value
    ) {
        if (this.stack.isEmpty()) {
            throw new IllegalStateException("Empty builder");
        }

        this.stack.peek().put(key, value);
        return this;
    }

    public MapBuilder endEntry() {
        if (this.stack.isEmpty()) {
            throw new IllegalStateException("Empty builder");
        }

        this.stack.pop();
        return this;
    }

    public Map<String, Object> build() {
        return this.stack.removeLast();
    }
}
